<template>
  <view class="flex-col">

    <car-info :value="form"></car-info>

    <view class="page-wrap" :class="canEdit?'bottom115':''">

      <view class="lineBottom10 page-section">
        <uni-section title="GPS维修信息" type="line"/>
      </view>

      <uni-forms ref="form" :value="form" labelWidth="auto" :labelPosition="canEdit?'top':'left'">

        <uni-forms-item name="expireGpsBrand" label="GPS服务期限:">
          <uni-easyinput v-if="canEdit" type="text" v-model="servicePeriod" disabled/>
          <text v-else class="text-value">{{ servicePeriod|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="gpsBrand" label="GPS品牌:">
          <uni-easyinput v-if="canEdit" type="text" v-model="form.gpsBrand" placeholder="请输入GPS品牌"/>
          <text v-else class="text-value">{{ form.gpsBrand|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="equipmentType" label="设备类型:">
          <zxz-uni-data-select
            v-model="form.equipmentType"
            dataKey="label"
            dataValue="value"
            v-if="canEdit"
            :localdata="dict.type.gps_device_type"></zxz-uni-data-select>
          <dict-tag v-else
                    :options="dict.type.gps_device_type"
                    :value="form.equipmentType"/>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="equipmentNo" label="设备编号:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入设备编号',
                                         validateTrigger: 'blur'
                                       }]">
          <uni-easyinput v-if="canEdit" type="text" v-model="form.equipmentNo"
                         placeholder="请输入设备编号"/>
          <text v-else class="text-value">{{ form.equipmentNo|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="sim" label="SIM卡号:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入SIM卡号',
                                         validateTrigger: 'blur'
                                       }]">
          <uni-easyinput v-if="canEdit" type="text" v-model="form.sim"
                         placeholder="请输入SIM卡号"/>
          <text v-else class="text-value">{{ form.sim|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="maintenanceTime" label="预约维修时间:" :rules="[{
                                         required: true,
                                         errorMessage: '请选择预约维修时间',
                                         validateTrigger: 'bind'
                                       }]">
          <uni-datetime-picker v-if="canEdit" type="datetime" return-type="string" v-model="form.maintenanceTime"/>
          <text v-else class="text-value">{{ form.maintenanceTime|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="maintenancePrice" label="维修费用:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入维修费用',
                                         validateTrigger: 'blur'
                                       }]">
          <uni-easyinput v-if="canEdit" type="digit" maxlength="12" v-model="form.maintenancePrice"
                         placeholder="请输入维修费用"/>
          <text v-else class="text-value">{{ form.maintenancePrice|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="faultIssues" label="故障问题:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入故障问题',
                                         validateTrigger: 'blur'
                                       }]">
          <uni-easyinput v-if="canEdit" type="text" v-model="form.faultIssues"
                         placeholder="请输入故障问题"/>
          <text v-else class="text-value">{{ form.faultIssues|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="maintenanceAddress" label="维修地点:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入维修地点',
                                         validateTrigger: 'blur'
                                       }]">
          <!-- <uni-easyinput v-if="canEdit" type="text" v-model="form.maintenanceAddress"
                         placeholder="请输入维修地点"/> -->
		  <province-city-district v-if="canEdit" v-model="form.maintenanceAddressCode" @change="citySelectionChange"></province-city-district>
          <text v-else class="text-value">{{ form.maintenanceAddress|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="sceneContacts" label="现场联系人:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入现场联系人',
                                         validateTrigger: 'blur'
                                       }]">
          <uni-easyinput v-if="canEdit" type="text" v-model="form.sceneContacts" placeholder="请输入现场联系人"/>
          <text v-else class="text-value">{{ form.sceneContacts|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item :required="canEdit" name="sceneContactsTel" label="现场联系人电话:" :rules="[{
                                         required: true,
                                         errorMessage: '请输入现场联系人电话',
                                         validateTrigger: 'blur'
                                       }]">
          <uni-easyinput v-if="canEdit" type="number" maxlength="12" v-model="form.sceneContactsTel"
                         placeholder="请输入现场联系人电话"/>
          <text v-else class="text-value">{{ form.sceneContactsTel|filterNull }}</text>
        </uni-forms-item>

        <uni-forms-item name="imageOss" label="上传照片:">
        </uni-forms-item>
        <image-common :disabled="!canEdit" :up-type="0" v-model="form.imageOss"></image-common>

        <uni-forms-item name="remark" label="备注:">
          <uni-easyinput v-if="canEdit" type="textarea" maxlength="200" v-model="form.remark"
                         placeholder="请输入备注"/>
          <text v-else class="text-value">{{ form.remark|filterNull }}</text>
        </uni-forms-item>

      </uni-forms>

    </view>

    <exam-flow v-if="!canEdit && form.flowId" :instanceId="form.flowId">
    </exam-flow>
    <view class="button-container" v-if="canEdit">
      <button class="btn-item" @click="submit">提 交</button>
    </view>
  </view>
</template>

<script>

import CarInfo from "@/pages/CarPage/gps/components/carInfo.vue";
import {carWorkOrderInfo, gpsMaintenance, saveCarGpsMaintenance, gpsSimInfo} from "@/api/gps/gpsList"
import UniSection from "@/uni_modules/uni-section/components/uni-section/uni-section.vue";
import ProvinceCityDistrict from "@/pages/CarPage/gps/components/provinceCityDistrict.vue";

var moment = require('@/utils/moment.js');

export default {
  components: {UniSection, CarInfo, ProvinceCityDistrict},
  dicts: ["gps_device_type"],
  data() {
    return {
      form: {},
      state: 'write',
      carIds: null,
      servicePeriod: ''
    }
  },
  computed: {
    canEdit() {
      return 'write' === this.state;
    }
  },
  onLoad(op) {
    console.log('op', op);
    this.state = op?.state ?? 'write';
    this.carIds = op?.carIds ?? null;

	let title = this.canEdit?'维修工单申请':'维修工单详情';
    if (this.carIds) {
      this.getOldData();
    }
    uni.setNavigationBarTitle({
      title
    })
  },
  methods: {
	  citySelectionChange(val) {
		console.log('val', val);
		if (val && val.length>0) {
		  this.form.maintenanceAddressCode = val.map(item=>item.value).join(",");
		  this.form.maintenanceAddress = val.map(item=>item.text).join("");
		} else {
		  this.form.maintenanceAddressCode = "";
		  this.form.maintenanceAddress = null;
		}
		this.$forceUpdate();
	  },
    getSim() {
      gpsSimInfo({
        carId: this.form.carId
      }).then(res => {

        console.log('---', parseInt("3年", 10))
        this.servicePeriod = this.calculateServicePeriod(res?.data[0]?.installTime ?? '', res?.data[0]?.gpsServicePeriod ?? '');
        // installTime  gpsServicePeriod
        // this.servicePeriod = res?.data[0]?installTime:gpsServicePeriod
        this.simList = res?.data[0]?.equipmentNo?.split(",")?.map((item, index) => {

          let simList = res?.data[0]?.simNo?.split(",");

          return {
            simNo: simList[index],
            equipmentNo: item,
          }

        }) ?? []
      })
    },
    calculateServicePeriod(installTime, gpsServicePeriod) {
      // 使用 moment.js 进行日期处理
      // const moment = require('moment');

      // 解析安装时间
      const installMoment = moment(installTime);

      // 解析保修期，提取数字部分，无论是否含有“年”字样
      const years = parseInt(gpsServicePeriod, 10);

      if (isNaN(years)) {
        return '无效的服务期限';
      }

      // 计算保修到期时间，不论字符串是否具有“年”字样都按年计算
      const serviceEndMoment = installMoment.add(years, 'years');

      // 获取当前时间
      const currentMoment = moment();

      // 比较当前时间与保修到期时间
      let servicePeriod = '';
      if (currentMoment.isBefore(serviceEndMoment)) {
        // 若当前时间在保修到期时间之前
        const remainingYears = serviceEndMoment.diff(currentMoment, 'years');
        // servicePeriod = `${remainingYears}年-质保期内`;
        servicePeriod = `${years}年-质保期内`;
      } else {
        // 若当前时间在保修到期时间之后
        const elapsedYears = currentMoment.diff(serviceEndMoment, 'years');
        // servicePeriod = `${elapsedYears}年-质保期外`;
        servicePeriod = `${years}年-质保期外`;
      }

      return servicePeriod;
    },
    getOldData() {
      carWorkOrderInfo({carIds: this.carIds, workOrderType: 14}).then(res => {
        let intentData = res.data[0];
        console.log('接到', intentData)

        if (!this.isEmpty(intentData)) {
          if (!this.isEmpty(intentData.businessDataId)) {
            //提报过，请求详情
            this.initData(intentData.businessDataId)
          } else {
            this.form = {...this.form, ...intentData}
            this.getSim()
          }
        }
      })
    },
    initData(id) {
      uni.showLoading();
      gpsMaintenance(id)
        .then((res) => {
          if (res.code == 200) {
            let data = res.data;
            this.form = {...this.form, ...data}
            this.getSim()
          }
        })
        .finally(() => {
          uni.hideLoading();
        });
    },

    submit() {
      this.form.contractNo = this.form.contractReportNumber;
      this.form.purchaseNo = this.form.procurementReportNumber;
      this.form.workId = this.form.id;

      this.$refs.form.validate().then(res => {
        uni.showLoading();
        saveCarGpsMaintenance(this.form).then(response => {
          uni.hideLoading();
          uni.$emit("refreshGps", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000)
        }).finally(f => {
			setTimeout(() => {
			  uni.hideLoading();
			}, 1000)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
